import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import net.sf.ghost4j.Ghostscript;

public class Test {
	public static void main(String[] args) {
		String dirname = "/home/fiorenzo/workspace_jboss_tools/PdfMerger/docs";
		String destdirname = "/home/fiorenzo/workspace_jboss_tools/TestGsMultiProcess/docs";
		File dir = new File(
				"/home/fiorenzo/workspace_jboss_tools/PdfMerger/docs");
		String nomeFilePDFUnico = dirname + "/fileUnico.pdf";
		String[] children = dir.list();

		// get Ghostscript instance
		Ghostscript gs = Ghostscript.getInstance();
		L4JOS logger = new L4JOS(Test.class.getCanonicalName());
		gs.setStdOut(logger);
		gs.setStdErr(logger);

		if (children == null) {
			// Either dir does not exist or is not a directory
		} else {
			List<String> files = new ArrayList<String>();
			Collections.sort(files);
			for (int i = 0; i < children.length; i++) {
				// Get filename of file or directory
				if (!".".equals(children[i]) && !"OLD".equals(children[i])) {
					System.out.println(children[i]);
					files.add(dirname + "/" + children[i]);

				}
			}
			// prepare Ghostscript interpreter parameters
			// refer to Ghostscript documentation for parameter usage

			// execute and exit interpreter
			// gs -dNOPAUSE -sDEVICE=pdfwrite -sOUTPUTFILE=firstANDsecond.pdf
			// -dBATCH first.pdf second.pdf
			List<String> gsArgsList = new LinkedList<String>();

			// -dUseCIEColor -sDEVICE=pdfwrite -sOutputFile='"
			gsArgsList.add("-dPDFX=true");
			gsArgsList.add("-dNOOUTERSAVE");
			gsArgsList.add("-dNOPAUSE");
			gsArgsList.add("-dBATCH");
			gsArgsList.add("-dSAFER");
			gsArgsList.add("-dPDFSETTINGS=/prepress");
			gsArgsList.add("-sDEVICE=pdfwrite");
			gsArgsList.add("-sOutputFile=" + destdirname + "/fileFinale.pdf");
			for (String string : files) {
				gsArgsList.add(string);
			}

			try {
				String[] options = new String[] {};
				options = gsArgsList.toArray(options);
				for (String string : options) {
					System.out.println(string);
				}

				gs.initialize(options);

				gs.exit();

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		System.out.println("test");

	}
}
